<template>
	<!-- 确定订单页面 -->
	<view class="confirm_order_container">
		<!-- 收货地址组件 -->
		<view class="address_component">
			<Address :noticeChoseAddress="noticeChoseAddress"></Address>
		</view>
		<!-- 商品卡片组件 -->
		<view class="goods_car_component">
			<GoodsCard></GoodsCard>
		</view>
		<!-- 订单参数和优惠券选择 -->
		<view class="order_params">
			<view class="param_item price_total">
				<view class="">商品总价</view>
				<view class="">￥{{ orderInfo.goodsInfo.price }}</view>
			</view>
			<view class="param_item coupon">
				<view class="">优惠券</view>
				<view class="right_text coupon_row">
					<view class="coupon_row_text" v-if="!usedCoupon" @click="gotoUseCoupon">
						{{ couponTextTip }}
					</view>
					<view class="coupon_row_text" v-if="usedCoupon" @click="gotoUseCoupon">
						优惠￥{{ disCountPrice }}
					</view>
					<view class="right_icon_box">
						<image class="right_icon" src="../../static/order/right.png" mode="widthFix"></image>
					</view>
				</view>
			</view>
			<view class="param_item yf">
				<view class="">邮费</view>
				<view class="right_text" style="font-size: 14px;">包邮</view>
			</view>
			<view class="param_item real_price">
				<view class="">实付</view>
				<view class="">￥{{ orderInfo.goodsInfo.price }}</view>
			</view>
		</view>
		<!-- 底部结算框 -->
		<view class="total_box">
			<view class="total_info">
				共 {{ orderInfo.number }} 件，合计：
				<span style="color: red;">￥<span style="font-size: 18px;">{{ orderInfo.goodsInfo.price }}</span></span>
			</view>
			<view class="total_btn">
				<button class="total_btn_B" type="default" @click="settleAccount">结算</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app"
import Address from "../../components/Address/Address.vue"
import GoodsCard from "../../components/GoodsCard/GoodsCard.vue"

// 地址组件是否选择了
let choseAddressFlag = ref(false);
let address = ref("");
let orderInfo = ref({goodsInfo:{}});

// 标识是否选择了优惠券
let usedCoupon = ref(false);
// 优惠券折扣价格
let disCountPrice = ref(0);
// 优惠券选择提示文本
let couponTextTip = ref("暂无可用");

onMounted(()=>{
	getOrderInfo(); // 获取订单信息
})

onShow(()=>{
	// 检查是否选择了优惠券
	checkCouponUse();
})

// 获取可用优惠券
async function getUseableCoupon(){
	// 获取用户信息
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	const res = await uni.$http.get(`/couponInfos/getUseAbleCouponInfosByUserId/${userInfo.userId}/${orderInfo.value.goodsInfo.goodsId}`);
	
	// 判断是否有可用优惠券
	if(res.data.code == 0){
		// 没有可用优惠券
		uni.setStorageSync("useAbleCoupon", JSON.stringify([]));
		couponTextTip.value = "暂无可用";
		return 1;
	}
	
	// 由于后端判断缺少"商品价格"字段的判断，需要再次根据商品字段作为过滤条件，二次过滤可用的优惠券
	let filterD = res.data.data.filter((item)=>{
		return orderInfo.value.goodsInfo.price >= item.limit
	})
	
	if(filterD.length == 0){
		couponTextTip.value = "暂无可用";
		uni.setStorageSync("useAbleCoupon", JSON.stringify([]));
		return 1;
	}
	
	couponTextTip.value = "去使用";
	
	// 将可用优惠券信息存储到本地
	uni.setStorageSync("useAbleCoupon", JSON.stringify(filterD));
}

// 检查是否选择了优惠券
function checkCouponUse(){
	let orderInfoN = JSON.parse(uni.getStorageSync("orderInfo"));
	
	// 重新赋值订单信息，更新出使用的优惠券信息
	orderInfo.value = orderInfoN;
	
	usedCoupon.value = orderInfoN.selectedCoupon;
	if(usedCoupon.value){
		disCountPrice.value = orderInfoN.couponInfo.value;
		// 动态显示扣减价格
		orderInfo.value.goodsInfo.price -= disCountPrice.value;
	}
}

// 跳转优惠券使用页面
function gotoUseCoupon(){
	if(couponTextTip.value != "暂无可用"){
		uni.navigateTo({
			url:"/subPkg2/use_coupon/use_coupon"
		})
	}
}

// 结算处理器
function settleAccount(){
	// 检查是否选择了地址
	if(!choseAddressFlag){
		uni.showToast({
			title: '请选择收货地址',
			icon: "none"
		});
		return 1;
	}
	
	// 封装请求参数，发送创建预支付订单请求
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	address.value = JSON.stringify(uni.getStorageSync("address"));
	let speciStr = JSON.stringify(orderInfo.value.specifications);
	
	// TODO 计算实付价格，检查是否使用优惠卷
	// if()
	
	let paramObj = {
		userId: userInfo.userId,
		goodsId: orderInfo.value.goodsInfo.goodsId,
		realPrice: orderInfo.value.goodsInfo.price,
		useCoupon: false,
		couponId: "",
		logisticsNumber:"", // 物流单号
		wxPayId:"", // 支付成功后的微信支付ID
		openId: userInfo.openId,
		shouldPrice: orderInfo.value.goodsInfo.price,
		goodsReceiveInfo: address.value ,// 收货信息
		specifications: speciStr, // 规格列表
		number: orderInfo.value.number
	}
	
	// 创建预支付订单请求
	createPrePayOrder(paramObj);
	
}

// 创建预支付订单
async function createPrePayOrder(paramObj){
	// 发送请求创建预支付订单，获取预支付订单参数调起微信支付
	const res = await uni.$http.post(`/pay/preOrderCreate`, paramObj);
	
	// 存储预支付参数
	uni.setStorageSync("prePayParam", res.data.data);
	
	// 唤起支付
	payActive(res.data.data);
}

function payActive(payParam){
	uni.requestPayment({
	    "nonceStr": payParam.wxNonceStr, // 随机字符串
	    "package": payParam.wxPackage,        // 预支付订单号
	    "signType":payParam.wxSignType,     // 签名类型
	    "timeStamp": payParam.wxTimeStamp,  // 时间戳
	    "paySign": payParam.wxPaySign, // 签名，这里用的 RSA 签名
	    success(res) {
			// 支付成功处，处理购物车商品，页面跳转
			console.log("支付成功!");
			// 后续处理逻辑和页面跳转
			successPayAfterHandle();
		},
	    fail(e) {
			// 失败回调
			console.log("支付失败");
			uni.showToast({
				icon:"none",
				title: '支付状态错误!'
			});
			
			// 跳转到待付款页面
			setTimeout(()=>{
				uni.navigateTo({
					url: `/subPkg2/order/order?state=0` // 跳转后选择状态为"待付款"
				})
			}, 1000)
		}
	})
}

// 成功支付的后续处理器
function successPayAfterHandle(){
	uni.showToast({
		icon:"none",
		title: '支付成功，即将跳转'
	});
	
	// 将商品从购物车中删除
	// 取出订单中的商品ID
	let buyGoodsId = orderInfo.value.goodsInfo.goodsId;
	// 遍历购物车商品, 删除购买了的商品
	let carGoodsList = JSON.parse(uni.getStorageSync("carList"));
	let afterFilterGoods = carGoodsList.filter((item)=>{ 
		return item.goodsInfo.goodsId != buyGoodsId
	})
	
	// 将处理之后的商品列表重新存储到购物车
	uni.setStorageSync("carList", JSON.stringify(afterFilterGoods));
	
	// 如果使用了优惠券，将优惠券扣除
	if(usedCoupon.value){
		// 使用了优惠券，扣除优惠券
		useCouponHandle();
	}
	
	// 页面跳转逻辑
	setTimeout(()=>{
		uni.switchTab({
			url:"/pages/my/my"
		})
	}, 1000)
}


// 扣除用户所使用的优惠券
async function useCouponHandle(){
	// 取出用户ID和所使用的优惠券ID
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	let couponInfo = orderInfo.value.couponInfo;
	
	// 构造请求参数对象
	let paramObj = {
		userId: userInfo.userId,
		couponId: couponInfo.couponId
	}
	
	// 执行扣减
	const res = await uni.$http.put("/couponInfos/useCoupon", paramObj);
	
}

// 获取订单信息
function getOrderInfo(){
	orderInfo.value = JSON.parse(uni.getStorageSync("orderInfo"));
	usedCoupon.value = orderInfo.value.selectedCoupon;
	getUseableCoupon() // 获取可用优惠券
}

// 收货地址组件通知修改是否选择了收货地址
function noticeChoseAddress(isSelect){
	if(isSelect){
		choseAddressFlag.value = isSelect;
	}
}



</script>

<style lang="scss" scoped>
.goods_car_component{
	width: 97%;
	margin: 0 auto;
	border-radius: 15rpx;
	margin-top: 20rpx;
	// border: solid red 1px;
}

.address_component{
	// border: solid red 1px;
}

.order_params{
	background-color: #fff;
	width: 97%;
	margin: 0 auto;
	border-radius: 15rpx;
	margin-top: 20rpx;
	font-size: 15px;
	padding: 20rpx 0px;
}

.param_item{
	display: flex;
	justify-content: space-between;
	padding: 30rpx 25rpx;
	position: relative;
}

.right_text{
	color: #515151;
}

.coupon_row_text{
	position: relative;
	right: 25rpx;
	font-size: 14px;
}

.right_icon_box{
	display: flex;
	justify-content: center;
	align-items: center;
}

.right_icon{
	width: 30px;
	position: absolute;
	right: 0px;
	
}

.coupon_row{
	display: flex;
}

.total_box{
	background-color: #fff;
	height: 100rpx;
	position: fixed;
	bottom: 0px;
	border-radius: 10rpx;
	width: 100vw;
	align-items: center;
	padding: 0px 15rpx;
	font-size: 15px;
	display: flex;
	justify-content: space-between;
}

.total_info{
	display: flex;
	align-items: center;
	height: 100%;
}

.total_btn{
	// border: solid red 1px;
	position: relative;
	right: 40rpx;
}

.total_btn_B{
	width: 150rpx;
	color: white;
	background-color: #ffa11c;
}
</style>
